package framework.sequential;

import framework.common.DeviceRequest;
import framework.common.DeviceResponse;

public class Client extends framework.common.Client {

	public Client(String user) {
		super(user);
	}

//	public void connect(DeviceServer dev) {
//		this.setDeviceName(dev.getDeviceName());
//	}

	public DeviceResponse request(DeviceRequest req) {
		// Step 1
		getHub().putRequest(req);
		// yield
		yield();
		// Step 2
		DeviceResponse res = getHub().getResponse(this);
		if (res.isError()) {
			throw new RuntimeException(res.getError());
		}
		return res;
	}

	public DeviceResponse request() {
		return request(getRequest());
	}

	public void yield() {
		int i = 0;
		while (! getHub().hasResponse(this) && i < 100) {
//			System.out.println("client wait for hub");
			HubServer hub = (HubServer)getHub();
			hub.process();
			i++;
		}
		if (i >= 100)
			throw new RuntimeException("Deadlocked");
	}


}
